package icu.minxin.binary;

import lombok.Data;

/**
 * @ClassName: BinaryTree
 * @Author AbelEthan
 * @Email AbelEthan@126.com
 * @Date 2021/6/4 下午3:35
 * @Description
 */
@Data
public class BinaryTree {

    private BinaryNode root;

    public BinaryTree() {
    }

    public BinaryNode find(Integer data){
        BinaryNode current = root;
        if (current == null){
            return null;
        }
        while (!current.getData().equals(data)){
            if (data < current.getData()){
                current = current.getLeftNode();
            }else {
                current = current.getRightNode();
            }
            if (current == null){
                return null;
            }
        }
        return current;
    }

    public void insert(Integer data){
        BinaryNode newNode = new BinaryNode(data);
        if (root == null){
            root = newNode;
            return;
        }
        BinaryNode current = root;
        BinaryNode parent = null;
        while (true){
            parent = current;
            if (data < current.getData()){
                current = current.getLeftNode();
                if (current == null){
                    parent.setLeftNode(newNode);
                    return;
                }
            }else {
                current = current.getRightNode();
                if (current == null){
                    parent.setRightNode(newNode);
                    return;
                }
            }
        }
    }
}
